<template>
  <div class="box">
    <div class="item" v-for="(item, index) in list" :key="index">
      <div class="ai" v-if="!item.isme">机器人---------{{ item.msg }}</div>

      <div class="me" v-else>我------{{ item.msg }}</div>
    </div>
    <div class="buttom">
      <input type="text" v-model="val" placeholder="请输入内容" /><button
        @click="btn"
      >
        发送
      </button>
      <div>
        <div class="aaa">
          这是从以前网络中找的聊天接口，通过 socket.io-client
          插件进行创建连接,不过并不是智能聊天
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { io } from 'socket.io-client'

export default {
  data () {
    return {
      contents: '',
      msg: '',
      meMsg: '',
      val: '',
      list: [
        {
          isme: true,
          msg: '罗某人'
        },
        {
          msg: '我是机器人'
        }
      ]
    }
  },
  created () {
    this.ws = io('http://toutiao.itheima.net', {
      transports: ['websocket']
    })
    this.ws.addEventListener('connect', () => {
      console.log('链接成功')
    })
    // 监听消息接收
    this.ws.addEventListener('message', data => {
      console.log('收到消息', data)
      this.list.push({
        isme: false,
        msg: data.msg
      })
    })
  },
  methods: {
    btn () {
      if (this.val !== '') {
        this.ws.emit('message', {
          msg: this.val,
          timestamp: Date.now()
        })
        this.list.push({
          isme: true,
          msg: this.val
        })
        this.val = ''
      }
    },
    dtnlj () {}
  }
}
</script>

<style lang="scss" scoped>
.box {
  width: 400px;
  height: 500px;
  border: 1px solid red;
  box-sizing: border-box;
  position: absolute;
  .ai {
    text-align: left;
  }
  .me {
    text-align: right;
  }
  .buttom {
    position: fixed;
    top: 500px;
  }
}
.aaa {
  margin-top: 20px;
}
</style>
